package server

import (
	"fmt"
	"go_im_server/user"
	"net"
	"strings"
	"sync"
)

type Server struct {
	Ip        string
	Port      int
	MapLock   sync.RWMutex
	OnlineMap map[string]*user.User
	HouseMap  map[string]*user.House
	Event     chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*user.User),
		HouseMap:  make(map[string]*user.House),
		Event:     make(chan string),
	}
	return server
}

func (s *Server) Start() {
	hostname := fmt.Sprintf("%s:%d", s.Ip, s.Port)
	conn, err := net.Listen("tcp", hostname)
	if err != nil {
		fmt.Println("net start err")
		return
	}
	fmt.Println(hostname)
	defer conn.Close()
	//监听消息事件
	go s.listenEvent()
	for {
		accept, err := conn.Accept()
		if err != nil {
			fmt.Println("get message err")
			continue
		}
		go s.handler(accept)
	}
}

func (s *Server) listenEvent() {
	for {
		event := <-s.Event
		if i := strings.Index(event, ":="); i <= 0 {
			fmt.Println("not find event")
			continue
		}
		fmt.Println("console : ", event)
		eventArray := strings.Split(event, ":=")
		eventRel := eventArray[1]
		connHost := eventArray[0]
		isSuccess := true
		switch eventRel {
		case "create_house":
			isSuccess = s.createHouse(connHost, eventArray[2], eventArray[3])
		case "del_house":
			isSuccess = s.delHouse(eventArray[2])
		case "send_msg":
			isSuccess = s.sendMessage(connHost, eventArray[2], eventArray[3])
		case "my_houses":
			isSuccess = s.myHouseList(connHost)
		case "user_list":
			go s.userList(connHost)
		}
		if !isSuccess {
			s.OnlineMap[connHost].C <- fmt.Sprintf("%s:%s", "server", "操作失败")
		}
	}
}

func (s *Server) userList(host string) bool {
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	for _, user := range s.OnlineMap {
		s.OnlineMap[host].C <- fmt.Sprintf("%s:%s", "server", user.Host)
	}
	return true
}

func (s *Server) myHouseList(host string) bool {
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	houses := s.OnlineMap[host].MyHouses()
	for houseName, house := range houses {
		var usersHostStr string
		for i := range house.Users {
			usersHostStr += house.Users[i].Host + ","
			if house.Users[i].Host == host {
			}
		}
		msg := houseName + ":[" + usersHostStr + "]"
		s.OnlineMap[host].C <- msg

	}
	return true
}

func (s *Server) delHouse(houseName string) bool {
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	users := s.HouseMap[houseName].Users
	delete(s.HouseMap, houseName)
	for i := range users {
		users[i].RemoveHouse(houseName)
		users[i].C <- fmt.Sprintf("%s:%s", "server", "你已退出群聊:["+houseName+"]")
	}
	return true
}

func (s *Server) sendMessage(host string, houseName string, msg string) bool {
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	house := s.HouseMap[houseName]
	if house == nil {
		return false
	}
	for i := range house.Users {
		msgRel := "[" + host + "]" + msg
		house.Users[i].C <- msgRel
	}
	return true
}

func (s *Server) createHouse(host string, toHost string, houseName string) bool {
	var fromUser *user.User
	var toUser []*user.User
	toHostSlice := strings.Split(toHost, ",")
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	for _, user := range s.OnlineMap {
		if user.Host == host {
			fromUser = user
		}
		for i := range toHostSlice {
			if user.Host == toHostSlice[i] {
				toUser = append(toUser, user)
			}
		}
	}
	if fromUser == nil || toUser == nil {
		fmt.Println("not found user")
	}
	//判断是否有重复房间名
	hasHouseName := false
	for house, _ := range s.HouseMap {
		if house == houseName {
			hasHouseName = true
		}
	}
	if hasHouseName {
		return false
	}
	houseUsers := []*user.User{fromUser}
	houseUsers = append(houseUsers, toUser...)
	house := user.NewHouse(houseName, houseUsers)
	s.HouseMap[houseName] = house
	return true
}

func (s *Server) handler(conn net.Conn) {
	fmt.Println(conn.RemoteAddr().String(), "into server")
	//上线创建用户
	user := user.NewUser(conn)
	s.OnLine(user)
	go func() {
		bytes := make([]byte, 4096)
		for {
			read, err := conn.Read(bytes)
			if read == 0 {
				//用户下线
				s.OffLine(user)
				return
			}
			if err != nil {
				fmt.Println("read msg error")
				return
			}
			addr := conn.RemoteAddr().String()
			msg := string(bytes[:read])
			msg = addr + ":=" + msg
			s.Event <- msg
		}
	}()
	select {}
}

func (s *Server) OnLine(u *user.User) {
	s.MapLock.Lock()
	defer s.MapLock.Unlock()
	s.OnlineMap[u.Host] = u
	for key, _ := range s.HouseMap {
		for i := range s.HouseMap[key].Users {
			if s.HouseMap[key].Users[i].Host == u.Host {
				s.HouseMap[key].Users[i] = u
				u.AddHouse(s.HouseMap[key])
			}
		}
	}
}

func (s *Server) OffLine(u *user.User) {
	s.MapLock.Lock()
	delete(s.OnlineMap, u.Host)
	s.MapLock.Unlock()
}
